const express = require('express');
const router = express.Router();
const opera = require('../utils/dbOperation')
const result = require('../utils/response')
const time = require('../utils/timeUtils')
const db = require('../utils/db')
const uid = require('../utils/getUid')
router.post('/list',async (req,res) =>{
  const data = req.body;

  const dbRel = (where) => {
    return new Promise((resolve, reject) => {
      opera.select("pro_project_database_rel",where,(results)=> resolve(results))
    })
  }

  const dbRelRes = await dbRel(data);
  const dbIds = [];
  dbRelRes.map(val => dbIds.push(val.database_id));

  const resData = await new Promise((resolve, reject) => {
    db.query('select * from pro_database where id in (?) order by id desc',[dbIds],back => resolve(back))
  })

  res.send(result.success(resData));
})

router.get('/allList',async (req,res) =>{
  opera.select("pro_database",{},(results)=>{
    res.send(result.success(results));
  },null,'create_time')
})


router.post('/detail',(req,res) => {
  const data = req.body;
  opera.findOne('pro_database',data,(back) =>{
    res.send(result.success(back))
  })
})

router.delete('/delete',(req,res) =>{
  const data = req.body;
  opera.del('pro_database',data,(back) => {
    res.send(result.success());
  })
})

router.put('/update',(req,res) =>{
  const data = req.body;
  const id = data.id;
  delete data.id;
  data.update_time = time.getNowFormatDate()
  opera.update('pro_database',data,{id:id},(back) => {
    res.send(result.success());
  })
})

router.post('/add',async (req,res) =>{
  const data = req.body;
  const projectId = data.projectId;
  delete data.projectId;
  data.id = uid();
  data.update_time = time.getNowFormatDate()
  data.create_time = time.getNowFormatDate()

  const insertData = (insertData) => {
    return new Promise((resolve, reject) => {
      opera.insert('pro_database',insertData,(back) => resolve(insertData.id))
    })
  }

  const dbId = await insertData(data);

  // const insertRel = (insertData) => {
  //   return new Promise((resolve, reject) => {
  //     opera.insert('pro_project_database_rel',insertData,(back) => resolve(insertData.id))
  //   })
  // }
  //
  // const relData = {
  //   id:uid(),
  //   project_id:projectId,
  //   database_id:dbId,
  //   create_time:time.getNowFormatDate(),
  //   update_time:time.getNowFormatDate()
  // }
  //
  // await insertRel(relData);

  res.send(result.success());

})

module.exports = router;
